import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.table.JBTable;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * Created by hx-pc on 17-1-9.
 */
public class AddressRepository extends AnAction {

    private JFrame frame;

    @Override
    public void actionPerformed(AnActionEvent anActionEvent) {
        new Thread(() -> {
            if (Objects.nonNull(frame)) {
                frame.removeAll();
                frame = null;
            }
            List<Resource> resources = findData();
            if (Objects.nonNull(resources)) {
                frame = createTable(resources);
            } else {
                throw new RuntimeException("返回数据为空");
            }
        }).start();
    }

    private List<Resource> findData() {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(getAPi());
            HttpResponse httpResponse = httpClient.execute(httpGet);
            String data = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            List<Resource> resources = toArray(data);
            resources.addAll(findLocalData(getLocalFile()));
            return resources;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Collection findLocalData(String path) {
        List<Resource> resources = new ArrayList<>();
        File file = new File(path);
        try {
            if (!file.exists()) {
                file.createNewFile();
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write("#name,url,port");
                fileWriter.flush();
                fileWriter.close();
            }
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String str = scanner.nextLine();
                if (!str.startsWith("#")) {
                    Resource resource = new Resource();
                    String[] strings = str.split(",");
                    resource.setName(strings[0] == null ? "空" : strings[0]);
                    resource.setUrl(strings[1] == null ? "空" : strings[1]);
                    resource.setPort(strings[2] == null ? "空" : strings[2]);
                    resources.add(resource);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resources;
    }

    private List<Resource> toArray(String content) {
        List<Resource> resources = new ArrayList<>();
        Gson gson = new Gson();
        //创建一个JsonParser
        JsonParser parser = new JsonParser();
        //通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
        JsonElement el = parser.parse(content);

        //把JsonElement对象转换成JsonArray
        JsonArray jsonArray = null;
        if (el.isJsonArray()) {
            jsonArray = el.getAsJsonArray();
        }

        //遍历JsonArray对象
        Iterator it = jsonArray.iterator();
        while (it.hasNext()) {
            JsonElement e = (JsonElement) it.next();
            //JsonElement转换为JavaBean对象
            resources.add(gson.fromJson(e, Resource.class));
        }
        return resources;
    }

    private JFrame createTable(List<Resource> resources) {
        int nameCount = 0;
        for (Resource resource : resources) {
            if (resource.getName().length() > nameCount) {
                nameCount = resource.getName().length();
            }
        }
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] gs = ge.getScreenDevices();
        GraphicsConfiguration[] gc = gs[0].getConfigurations();
        Rectangle bounds = gc[0].getBounds();
        JFrame frame = new JFrame("AddressRepository");
        TableModel dataModel = new AbstractTableModel() {
            public int getColumnCount() {
                return 3;
            }

            public int getRowCount() {
                return resources.size();
            }

            public Object getValueAt(int row, int col) {
                if (col % 3 == 1) {
                    return resources.get(row).getUrl();
                } else if (col % 3 == 0) {
                    return resources.get(row).getName();
                } else if (col % 3 == 2) {
                    return resources.get(row).getPort() == null ? "默认" : resources.get(row).getPort();
                }
                return row * col;
            }

            @Override
            public String getColumnName(int column) {
                if (column == 0) {
                    return "name";
                } else if (column == 1) {
                    return "url";
                } else if (column == 2) {
                    return "port";
                }
                return super.getColumnName(column);
            }
        };
        JBTable jbTable = new JBTable(dataModel);
        //FontFamily.getAllFontFamilies()[34].getFamilyName()
        jbTable.setFont(new Font("仿宋", Font.BOLD, 14));
        jbTable.setRowHeight(20);
        TableColumn firstColumn = jbTable.getColumnModel().getColumn(0);
        firstColumn.setPreferredWidth(nameCount * 15);
        TableColumn secColumn = jbTable.getColumnModel().getColumn(1);
        secColumn.setPreferredWidth(300);
        TableColumn thrColumn = jbTable.getColumnModel().getColumn(2);
        thrColumn.setPreferredWidth(100);
        jbTable.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 27) {
                    frame.dispose();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }
        });
        int width = nameCount * 14 + 300 + 100;
        int height = 400;
        jbTable.setAutoResizeMode(JBTable.AUTO_RESIZE_ALL_COLUMNS);
        jbTable.setColumnSelectionAllowed(true);
        jbTable.setVisible(true);
        JScrollPane jScrollPane = new JBScrollPane(jbTable);
        jScrollPane.setVisible(true);
        jScrollPane.show();
        frame.setLocation(new Double(bounds.getWidth()).intValue() / 2 - width / 2, new Double(bounds.getHeight()).intValue() / 2 - height / 2);
        frame.setSize(width, height);
        frame.add(jScrollPane);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
        frame.show();
        return frame;
    }


    public String getAPi() {
        File file = new File("./.addressrepository-conf");
        try {
            if (!file.exists()) {
                file.createNewFile();
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write("repo_url http://192.168.31.116:8889/resource/db/all\n");
                fileWriter.write("localfile_url ./.localrepository");
                fileWriter.flush();
                fileWriter.close();
            }
            Properties properties = new Properties();
            properties.load(new FileInputStream(file));
            return properties.getProperty("repo_url");
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("不存在的文件" + file.getAbsolutePath());
    }

    public String getLocalFile() {
        File file = new File("./.addressrepository-conf");
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream(file));
            return properties.getProperty("localfile_url");
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("不存在的文件" + file.getAbsolutePath());
    }
}
